<script lang="ts">
import Vue from 'vue'
import {getWordAudio} from '@/api/wordHelper'

export default Vue.extend({
  name: 'audioPlayback',
  props: {
    wordId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      playing: false
    }
  },
  methods: {
    handleClick() {
      getWordAudio({'wordId': this.wordId}).then(res => {
        this.playAudioByUrl(res)
      })
    },
    playAudioByUrl(url) {
      if (!url) return

      const audio = new Audio(url)
      audio.autoplay = true
      this.playing = true

      // 播放成功处理
      audio.play()
        .then(() => {
        })
        .catch(err => {
          console.warn('音频播放失败：', err)
          this.$message.error('音频播放失败')
        }).finally(() => {
        })

      // 监听播放结束事件
      audio.addEventListener('ended', () => {
        audio.remove()
        this.playing = false
      })

      // 可选：监听播放出错
      audio.addEventListener('error', (e) => {
        console.error('播放音频时发生错误', e)
        this.$message.error('播放音频时发生错误')
      })
    }

  }
})
</script>

<template>
  <div>
    <img  v-if="!playing" style="cursor: pointer" @click="handleClick" src="@/assets/speaker.svg" alt="speaker" />
    <div v-else class="audio-wave">
      <span class="bar bar1"></span>
      <span class="bar bar2"></span>
      <span class="bar bar3"></span>
    </div>
  </div>
</template>

<style scoped lang="scss">

.audio-wave {
  display: flex;
  align-items: flex-end;
  height: 19.23px;
  width: 16px;
  gap: 4px;
}

.bar {
  width: 4px;
  background-color: #409EFF; /* 蓝色可自定义 */
  animation: wave 1s infinite ease-in-out;
  border-radius: 2px;
}

.bar1 {
  animation-delay: 0s;
}

.bar2 {
  animation-delay: 0.2s;
}

.bar3 {
  animation-delay: 0.4s;
}

@keyframes wave {
  0%, 100% {
    height: 10%;
  }
  50% {
    height: 100%;
  }
}

</style>
